package cn.tedu.charging.order.amqp;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 封装底层客户端 实现生产发送的对象
 */
@Component
@Slf4j
public class ProducerClient<T> {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //发送业务消息 目的交换机名称 路由key 消息对象T message
    public void send(String destination,String routingKey,T msg){
        this.send(destination,routingKey,msg,null);
    }
    //发送消息 目的交换机 路由key 消息对象T headers
    public void send(String destination, String routingKey, T msg, Map<String,Object> headers){
        //1.装配成message对象 如果有头就携带 没有就不带
        Message message=null;
        if (headers!=null){
            MessageProperties properties=new MessageProperties();
            properties.setHeaders(headers);
            message= MessageBuilder.withBody(serializser(msg)).andProperties(properties).build();
        }else{
            message= MessageBuilder.withBody(serializser(msg)).build();
        }
        //2.发送到目标
        rabbitTemplate.convertAndSend(destination,routingKey,message);
    }
    //序列化方法serializer
    public static <T> byte[] serializser(T msg){
        //1.所有消息类型 转化成json 字符串 获取byte属性
        return JSON.toJSONString(msg).getBytes(StandardCharsets.UTF_8);
    }
    //反序列化方法deserializer
    public static <T> T deserializer(byte[] body,Class<T> clazz){
        //将body转化成字符串 解析对象
        String json = new String(body, StandardCharsets.UTF_8);
        return JSON.parseObject(json, clazz);
    }
    //反序列化方法
    public static <T> T deserializer(String json,Class<T> clazz){
        //将body转化成字符串 解析对象
        return JSON.parseObject(json, clazz);
    }
}
